<template>
  <div class="my-campaigns-page">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1 class="logo">众筹平台</h1>
          <el-menu
            mode="horizontal"
            :default-active="activeMenu"
            class="nav-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="/home">首页</el-menu-item>
            <el-menu-item index="/campaigns">众筹列表</el-menu-item>
            <el-menu-item index="/create">创建众筹</el-menu-item>
            <el-menu-item index="/my-campaigns">我的众筹</el-menu-item>
          </el-menu>
          <div class="user-info">
            <span class="username">{{ user.username }}</span>
            <el-button type="text" @click="logout">退出</el-button>
          </div>
        </div>
      </el-header>
      
      <el-main class="main-content">
        <div class="my-campaigns-container">
          <el-alert
            v-if="!walletConnected"
            title="提示"
            type="warning"
            description="请先连接钱包以查看您的众筹项目"
            show-icon
            :closable="false"
            style="margin-bottom: 20px;"
          >
            <el-button type="primary" size="small" @click="connectWallet">
              连接钱包
            </el-button>
          </el-alert>

          <el-tabs v-model="activeTab" @tab-click="handleTabClick" v-if="walletConnected">
            <!-- 我创建的众筹 -->
            <el-tab-pane label="我创建的众筹" name="created">
              <div class="tab-header">
                <h3>我创建的众筹项目 ({{ createdCampaigns.length }})</h3>
                <el-button type="primary" icon="el-icon-refresh" @click="loadCreatedCampaigns">
                  刷新
                </el-button>
              </div>

              <div v-loading="loadingCreated" class="campaigns-grid">
                <el-empty v-if="createdCampaigns.length === 0 && !loadingCreated" description="您还没有创建任何众筹项目">
                  <el-button type="primary" @click="$router.push('/create')">创建众筹</el-button>
                </el-empty>
                
                <el-card
                  v-for="campaign in createdCampaigns"
                  :key="campaign.id"
                  class="campaign-card"
                  shadow="hover"
                  @click.native="goToDetail(campaign.id)"
                >
                  <div class="campaign-status">
                    <el-tag :type="getStatusType(campaign.status)">
                      {{ campaign.status }}
                    </el-tag>
                  </div>
                  
                  <h3 class="campaign-name">{{ campaign.name }}</h3>
                  <p class="campaign-description">{{ campaign.description }}</p>
                  
                  <div class="campaign-progress">
                    <el-progress
                      :percentage="campaign.progress"
                      :color="getProgressColor(campaign.progress)"
                    />
                    <div class="progress-info">
                      <span>已筹集: {{ campaign.pledged }} ETH</span>
                      <span>目标: {{ campaign.goal }} ETH</span>
                    </div>
                  </div>
                  
                  <div class="campaign-actions">
                    <el-button
                      v-if="campaign.status === 'Successful' && !campaign.claimed"
                      type="success"
                      size="small"
                      @click.stop="handleClaim(campaign.id)"
                    >
                      提取资金
                    </el-button>
                    <el-tag v-if="campaign.claimed" type="success">已提取</el-tag>
                  </div>
                </el-card>
              </div>
            </el-tab-pane>

            <!-- 我支持的众筹 -->
            <el-tab-pane label="我支持的众筹" name="backed">
              <div class="tab-header">
                <h3>我支持的众筹项目 ({{ backedCampaigns.length }})</h3>
                <el-button type="primary" icon="el-icon-refresh" @click="loadBackedCampaigns">
                  刷新
                </el-button>
              </div>

              <div v-loading="loadingBacked" class="campaigns-grid">
                <el-empty v-if="backedCampaigns.length === 0 && !loadingBacked" description="您还没有支持任何众筹项目">
                  <el-button type="primary" @click="$router.push('/campaigns')">浏览众筹</el-button>
                </el-empty>
                
                <el-card
                  v-for="campaign in backedCampaigns"
                  :key="campaign.id"
                  class="campaign-card"
                  shadow="hover"
                  @click.native="goToDetail(campaign.id)"
                >
                  <div class="campaign-status">
                    <el-tag :type="getStatusType(campaign.status)">
                      {{ campaign.status }}
                    </el-tag>
                  </div>
                  
                  <h3 class="campaign-name">{{ campaign.name }}</h3>
                  <p class="campaign-description">{{ campaign.description }}</p>
                  
                  <div class="campaign-progress">
                    <el-progress
                      :percentage="campaign.progress"
                      :color="getProgressColor(campaign.progress)"
                    />
                    <div class="progress-info">
                      <span>已筹集: {{ campaign.pledged }} ETH</span>
                      <span>目标: {{ campaign.goal }} ETH</span>
                    </div>
                  </div>

                  <div class="my-pledge">
                    <i class="el-icon-wallet"></i>
                    我的投资: {{ campaign.myPledge }} ETH
                  </div>
                  
                  <div class="campaign-actions">
                    <el-button
                      v-if="campaign.status === 'Failed' && campaign.myPledge > 0"
                      type="warning"
                      size="small"
                      @click.stop="handleRefund(campaign.id)"
                    >
                      申请退款
                    </el-button>
                  </div>
                </el-card>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import web3Helper from '@/utils/web3';
import contractService from '@/api/contract';

export default {
  name: 'MyCampaigns',
  data() {
    return {
      user: {},
      walletConnected: false,
      activeTab: 'created',
      createdCampaigns: [],
      backedCampaigns: [],
      loadingCreated: false,
      loadingBacked: false,
      activeMenu: '/my-campaigns'
    };
  },
  created() {
    this.loadUserInfo();
    this.checkUrlParams();
    this.checkWalletConnection();
  },
  methods: {
    loadUserInfo() {
      const userStr = localStorage.getItem('user');
      if (userStr) {
        this.user = JSON.parse(userStr);
      }
    },
    
    checkUrlParams() {
      // 检查 URL 参数，支持从 Home 页面跳转时切换标签
      const tab = this.$route.query.tab;
      if (tab === 'backed') {
        this.activeTab = 'backed';
      } else if (tab === 'created') {
        this.activeTab = 'created';
      }
    },
    
    async checkWalletConnection() {
      if (web3Helper.getAccount()) {
        this.walletConnected = true;
        // 根据当前标签加载相应的数据
        if (this.activeTab === 'backed') {
          await this.loadBackedCampaigns();
        } else {
          await this.loadCreatedCampaigns();
        }
      }
    },
    
    async connectWallet() {
      try {
        await web3Helper.connect();
        this.walletConnected = true;
        await contractService.init();
        await this.loadCreatedCampaigns();
        this.$message.success('钱包连接成功！');
      } catch (error) {
        this.$message.error(error.message || '钱包连接失败');
      }
    },
    
    async loadCreatedCampaigns() {
      if (!this.walletConnected) return;
      
      this.loadingCreated = true;
      try {
        await contractService.init();
        const account = web3Helper.getAccount();
        const ids = await contractService.getUserCreatedCampaigns(account);
        
        const campaigns = [];
        for (const id of ids) {
          try {
            const campaign = await contractService.getCampaign(id);
            const status = await contractService.getCampaignStatus(id);
            
            const pledged = parseFloat(campaign.pledged);
            const goal = parseFloat(campaign.goal);
            const progress = goal > 0 ? Math.min((pledged / goal) * 100, 100) : 0;
            
            campaigns.push({
              id,
              ...campaign,
              status,
              progress: Math.round(progress)
            });
          } catch (error) {
            console.error(`加载众筹 ${id} 失败:`, error);
          }
        }
        
        this.createdCampaigns = campaigns.reverse();
      } catch (error) {
        console.error('加载我创建的众筹失败:', error);
        this.$message.error(error.message || '加载我创建的众筹失败');
      } finally {
        this.loadingCreated = false;
      }
    },
    
    async loadBackedCampaigns() {
      if (!this.walletConnected) return;
      
      this.loadingBacked = true;
      try {
        await contractService.init();
        const account = web3Helper.getAccount();
        const ids = await contractService.getUserBackedCampaigns(account);
        
        const campaigns = [];
        for (const id of ids) {
          try {
            const campaign = await contractService.getCampaign(id);
            const status = await contractService.getCampaignStatus(id);
            const myPledge = await contractService.getPledgedAmount(id, account);
            
            const pledged = parseFloat(campaign.pledged);
            const goal = parseFloat(campaign.goal);
            const progress = goal > 0 ? Math.min((pledged / goal) * 100, 100) : 0;
            
            campaigns.push({
              id,
              ...campaign,
              status,
              progress: Math.round(progress),
              myPledge: parseFloat(myPledge)
            });
          } catch (error) {
            console.error(`加载众筹 ${id} 失败:`, error);
          }
        }
        
        this.backedCampaigns = campaigns.reverse();
      } catch (error) {
        console.error('加载我支持的众筹失败:', error);
        this.$message.error(error.message || '加载我支持的众筹失败');
      } finally {
        this.loadingBacked = false;
      }
    },
    
    handleTabClick(tab) {
      if (tab.name === 'created' && this.createdCampaigns.length === 0) {
        this.loadCreatedCampaigns();
      } else if (tab.name === 'backed' && this.backedCampaigns.length === 0) {
        this.loadBackedCampaigns();
      }
    },
    
    async handleClaim(id) {
      this.$confirm('确定要提取资金吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(async () => {
        try {
          await contractService.claim(id);
          this.$message.success('资金提取成功！');
          await this.loadCreatedCampaigns();
        } catch (error) {
          console.error('提取资金失败:', error);
          this.$message.error(error.message || '提取资金失败');
        }
      }).catch(() => {});
    },
    
    async handleRefund(id) {
      try {
        await contractService.refund(id);
        this.$message.success('退款成功！');
        await this.loadBackedCampaigns();
      } catch (error) {
        console.error('退款失败:', error);
        this.$message.error(error.message || '退款失败');
      }
    },
    
    goToDetail(id) {
      this.$router.push(`/campaign/${id}`);
    },
    
    getStatusType(status) {
      const typeMap = {
        'Active': 'success',
        'Successful': 'success',
        'Failed': 'danger',
        'Cancelled': 'warning',
        'Not Started': 'info'
      };
      return typeMap[status] || 'info';
    },
    
    getProgressColor(percentage) {
      if (percentage < 30) return '#F56C6C';
      if (percentage < 70) return '#E6A23C';
      return '#67C23A';
    },
    
    handleMenuSelect(index) {
      this.$router.push(index);
    },
    
    logout() {
      this.$confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('user');
        web3Helper.disconnect();
        this.$message.success('已退出登录');
        this.$router.push('/login');
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.my-campaigns-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.logo {
  font-size: 24px;
  color: #409EFF;
  margin: 0;
  margin-right: 40px;
}

.nav-menu {
  flex: 1;
  border: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.username {
  font-weight: bold;
  color: #333;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.tab-header h3 {
  margin: 0;
  color: #333;
}

.campaigns-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.campaign-card {
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.campaign-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}

.campaign-status {
  position: absolute;
  top: 15px;
  right: 15px;
}

.campaign-name {
  margin: 0 0 15px 0;
  font-size: 20px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.campaign-description {
  color: #666;
  margin-bottom: 20px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.campaign-progress {
  margin-bottom: 15px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.my-pledge {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #409EFF;
  margin-top: 10px;
  font-weight: bold;
}

.my-pledge i {
  font-size: 16px;
}

.campaign-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>

